package com.nts.pmchelperdemo3.util;

import com.nts.pmchelperdemo3.constant.MessageConstant;
import com.nts.pmchelperdemo3.constant.OrderStatusConstant;
import com.nts.pmchelperdemo3.entity.Order;
import com.nts.pmchelperdemo3.exception.OrderNotFoundException;
import com.nts.pmchelperdemo3.exception.TransitionErrorException;
import com.nts.pmchelperdemo3.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单排序工具类（按需求规则排序）
 * 排序规则：客户优先级（降序）→ 截止日期（升序）→ 开始日期（升序）
 */

@Service
public class OrderSortUtil {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 对订单列表进行排序
     * @param orders 待排序订单列表
     * @return 排序后的订单列表
     */
    public static List<Order> sortOrders(List<Order> orders) {
        if (orders == null || orders.isEmpty()) {
            return orders;
        }

        // 按规则排序：优先级（高→低）→ 截止日期（早→晚）→ 开始日期（早→晚）
        return orders.stream()
                .sorted(Comparator.comparingInt(Order::getPriority).reversed()
                        .thenComparing(Order::getEndTime)
                        .thenComparing(Order::getStartTime))
                .collect(Collectors.toList());
    }

    /**
     * 判断两个订单是否符合合并条件（相同刀具+交付日期差≤3天）
     * @param order1 订单1
     * @param order2 订单2
     * @return 是否可合并
     */
    public static boolean isMergeable(Order order1, Order order2) {
        if (order1 == null || order2 == null) {
            return false;
        }

        // 条件1：刀具名称相同
        if (!order1.getToolName().equals(order2.getToolName())) {
            return false;
        }

        // 条件2：交付日期差≤3天（绝对值）
        long dayDiff = Math.abs(DateUtil.getWorkDayCount(order1.getEndTime(), order2.getEndTime()));
        return dayDiff <= 3;
    }
    public void updateOrderStatus(Long orderId, Integer newStatus) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new OrderNotFoundException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 状态流转校验（复用原逻辑）
        List<Integer> allowedStatuses = OrderStatusConstant.VALID_TRANSITIONS.get(order.getStatus());
        if (allowedStatuses == null || !allowedStatuses.contains(newStatus)) {
            throw new TransitionErrorException(MessageConstant.TRANSITION_ERROR);
        }
        order.setStatus(newStatus);
        orderMapper.updateById(order);
    }
}
